package main

import (
	"context"
	_ "peilian-api/bootstrap"
	"strings"

	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
	"peilian-api/app/global/common"
	"peilian-api/app/global/log"
	"peilian-api/app/global/variable"
	"peilian-api/app/model"
	"peilian-api/app/services/user_service"
	"peilian-api/utils/tools"

	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
)

func GetToken() (string, error) {
	appid := "wx57e64b80f2dbc79b"
	secret := "c2ef59b633cf21e74c02f45da1bd6202"

	// 先获取token 是否存在
	// sc := variable.DB.Redis.Get(appid)
	// access_token, err := sc.Result()
	// if err == nil && len(access_token) > 0 {
	// 	return access_token, nil
	// }

	// 调用api 生成token

	tokenUrl := "https://api.weixin.qq.com/cgi-bin/token"
	getUrl := fmt.Sprintf("%s?grant_type=client_credential&appid=%s&secret=%s", tokenUrl, appid, secret)
	resp, err := http.Get(getUrl)
	if err != nil {
		return "", fmt.Errorf("token生成失败")
	}
	if resp != nil {
		defer resp.Body.Close()
	}
	res := make(map[string]interface{})
	err = tools.ReadResponseBody(resp, &res)
	if err != nil {
		return "", fmt.Errorf("token解析失败")
	}
	accessToken := res["access_token"].(string)
	return accessToken, nil
}

// 通过code获取phone
func GetUserPhoneNumberByCode(code string) (string, error) {
	// 获取token
	accessToken, err := GetToken()
	if err != nil {
		return "", err
	}
	params := map[string]string{"code": code}
	reqData, _ := json.Marshal(params)
	resp, err := http.Post(
		fmt.Sprintf("%s?access_token=%s", variable.Config.Wx.UserPhoneNumber, accessToken),
		"application/json",
		bytes.NewReader(reqData),
	)
	if err != nil {
		return "", err
	}
	if resp != nil {
		defer resp.Body.Close()
	}
	res := model.PhoneInfoResp{}
	err = tools.ReadResponseBody(resp, &res)
	if err != nil {
		return "", err
	}
	if res.Errcode != 0 {
		return "", fmt.Errorf(res.Errmsg)
	}
	return res.PhoneInfo.PurePhoneNumber, nil
}

// 发送消息

func main() {
	// s, err := GetToken()
	// if err != nil {
	// 	fmt.Println("-----")
	// }
	// fmt.Println(s)
	c := &gin.Context{}
	uuidStr := strings.ReplaceAll(uuid.NewString(), "-", "")
	c.Set(common.TraceKey, context.WithValue(context.Background(), common.TraceKey, &log.Trace{TraceId: uuidStr, SpanId: uuidStr, Caller: "/judgeVideoGenerate"}))
	err := new(user_service.BdService).OptionTeacherData(c)
	fmt.Println(err)
}
